package com.demo.security;

import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 11:29
 */
public class AESUtil {

    /**
     * 生成AES密钥需要的key
     *
     * @return
     */
    public static String genKeyAES() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        String base64Str = Base64Util.byte2base64(secretKey.getEncoded());
        return base64Str;
    }

    /**
     * 生成AES密钥
     *
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static SecretKey loadKeyAES(String base64Key) throws IOException {
        byte[] bytes = Base64Util.base642byte(base64Key);
        SecretKey secretKey = new SecretKeySpec(bytes, "AES");
        return secretKey;
    }

    /**
     * AES加密
     *
     * @param source
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptAES(byte[] source, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(source);
        return bytes;
    }

    /**
     * AES解密
     *
     * @param source
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptAES(byte[] source, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(source);
        return bytes;
    }
}
